import Taro from '@tarojs/taro'
import { Component } from 'react'
import { View, Image, Text, Button } from '@tarojs/components'
import { showToast, strLength } from '@/utils'
import { AtInput, AtListItem,AtMessage, AtModalHeader, AtModalContent, AtModalAction } from 'taro-ui'
import { connect } from 'react-redux'
import api from '@/api'
import S from '@/spx'
import UploadUtil from '@/utils/UploadUtil'
import './index.scss'
import { SpToast } from '@/components'
import { updateUserInfo } from '@/store/user'
const head = require('../../assets/imgs/my/head.png')
const defaultshop = require('@/assets/imgs/defaultshop.png')
@connect(({ planSelection, user }) => ({
  planSelection,
  userinfo: user.userInfo
}),
  (dispatch) => ({ dispatch })
)
export default class My extends Component {
  constructor() {
    super()
    this.state = {
      username: '',
      mobile: '', // 手机
      head_portrait: '', // 个人头像
      work_userid: '', // 企业微信id
      distributors: null,
      isOpened: false,
      logintype: '',
      logintypeNum: '',
    }
  }

  componentDidMount() {
    const type = S.getLoginType()
    console.log('---------type',type)
    this.setState({
      logintypeNum: type
    })
    this.getMyInfoHandle()

  }
  componentDidShow() {
    this.getMyInfoHandle()
  }

  async getMyInfoHandle() {
    const obj = {
      is_app: 1
    }
    const result = await api.my.getMyinfo(obj)
    console.log(result)
    const { username, mobile, head_portrait, work_userid, distributors, logintype } = result
    await this.setState({
      username,
      mobile,
      head_portrait,
      work_userid,
      distributors,
      logintype
    })

    if (logintype == 'distributor') {
      distributors && this.format_distributors(distributors)
    } else {
      let user = {}
      user.memberInfo = result
      const merchant = await api.shop.getEnterpriseInfo()
      user.memberInfo = {
        ...result,
        ...merchant
      }
      await this.props.dispatch(updateUserInfo(user))
    }
  }
  format_distributors(data) {
    const { dispatch } = this.props
    const { activeShop } = this.props.planSelection
    console.log(this.props.userinfo)
    if (activeShop) {
      let { distributor_id } = activeShop
      console.log(distributor_id)
      const result = data.filter((item) => {
        return item.distributor_id == distributor_id
      })
      this.setState(
        {
          distributors: result[0]
        },
        () => {
          console.log(this.state.distributors)
          let user = {}
          user.memberInfo = this.state.distributors
          let sss = {
            'logintype': this.state.logintype,
            'username': this.state.username,
            'head_portrait': this.state.head_portrait,

          }
          user.memberInfo = {
            ...sss,
            ...this.state.distributors
          }
          dispatch(updateUserInfo(user))
        }
      )
    }
  }

  notUpdate(message) {
    S.toast(`${message}暂不支持修改！`)
  }
  loginOut(message) {
    Taro.showModal({
      title: '退出登录提示',
      content: '确定要退出登录？',
      success: function (res) {
        if (res.confirm) {
          S.logout()
          S.login()
        } else if (res.cancel) {

        }
      }
    })
    // this.setState({
    //   isOpened: true
    // })
  }
  handleCancel() {
    this.setState({
      isOpened: false
    })
  }
  handleConfirm() {
    S.logout()
    S.login()
  }
  // 上传头像
  async handleAvatar() {
    if (Taro.getEnv() == 'SAPP') {
      // alert(plus.device.vendor)  
      this.requestLocation()

  }
    const { tempFiles = [] } = await Taro.chooseImage({
      count: 1
    })
    console.log('tempFiles', tempFiles)
    const upload = new UploadUtil()

    console.log('upload', upload)

    const result = await upload.uploadImg(tempFiles[0])
    this.handleAvatarSuccess(result, tempFiles[0].originalFileObj)
  }
  // 申请权限
  requestLocation() {
    console.log(2222)
    let that = this
    plus.android.requestPermissions(['android.permission.READ_EXTERNAL_STORAGE'], function (e) {
        if (e.deniedAlways.length > 0) {	//权限被永久拒绝
            // 弹出提示框解释为何需要权限，引导用户打开设置页面开启
            Taro.showModal({
                title: '无法访问您的存储空间',
                content: '更换头像功能需要访问到您的存储空间，存储空间权限被拒绝，您可以去设置页面设置您的存储空间权限',
                success: function (res) {
                    if (res.confirm) {
                    } else if (res.cancel) {
                    }
                }
            })
            console.log('Always Denied!!! ' + e.deniedAlways.toString());

        }
        if (e.deniedPresent.length > 0) {	//权限被临时拒绝
            // 弹出提示框解释为何需要定位权限，可再次调用plus.android.requestPermissions申请权限
            console.log('Present Denied!!! ' + e.deniedPresent.toString());
        }
        if (e.granted.length > 0) {	//权限被允许
            //调
            console.log('Granted!!! ' + e.granted.toString());
        }
    }, function (e) {
        console.log('Request Permissions error:' + JSON.stringify(e));
    });
    if (plus.device.vendor == 'HUAWEI') {
        Taro.atMessage({
            'message': '更换头像功能需要访问到您的存储空间或者是您的相机进行拍照更换头像',
        })
    }
}
  async handleAvatarSuccess(res, file) {
    console.log('handleAvatarSuccess', res)
    let uploadParams = {
      image_cat_id: 2, //图片分类必填,必须为整数
      image_name: file.name, //图片名称必填,不能超过50个字符
      image_url: res.data ? JSON.parse(res.data).data.image_url : res.key, //图片链接必填
      image_type: file.type, //图片分类长度不能超过20个字符
      storage: 'image' //图片id必填
    }
    console.log(uploadParams)
    const result = await api.qiniu.uploadQiniuPic(uploadParams)
    this.setState({
      head_portrait: result.image_full_url
    })
    const resultConfig = await api.my.updateInfo({
      head_portrait: this.state.head_portrait
    })
    // showToast('修改成功')
  }

  photoUpdate() {
    let input = document.createElement('input')
    input.setAttribute('type', 'file')
    console.log(input)
    input.click()
    input.addEventListener('change', async function () {
      const result = await api.my.updatePhoto({
        head_portrait: input.files[0]
      })
      console.log(result)

      console.log(input.files[0])
      input.remove()
    })
  }

  switchShopHandle() {
    Taro.reLaunch({
      url: '/pages/planSelection/index'
    })
  }

  usernameChange(value) {
    let str = strLength(value)
    if (str > 20) {
      return S.toast(`最多输入10个字符喔`)
    }
    this.setState({
      username: value
    })
  }

  async usernameBlur() {
    const result = await api.my.updateInfo({
      username: this.state.username
    })
    console.log(result)
  }

  onSubmit(event) {
    console.log(this.state.username)
    showToast(event)
    event.preventDefault()
    return false
  }

  render() {
    const { username, work_userid, mobile, head_portrait, distributors, isOpened } = this.state
    return (
      <View className='page-my'>
        <View className='top'>
          <Image
            className='info-img'
            src={require('../../assets/imgs/my/zyk_bg.png')}
          ></Image>
          <View className='info'>
            <View className='photo'>
              {!!this.state.logintypeNum ? (
                <Image src={(distributors && distributors.logo) || defaultshop}></Image>
              ) : (
                <Image src={head_portrait || head}></Image>)}
            </View>
            <View className='content'>
              <View className='title'>{!!this.state.logintypeNum ? (distributors && distributors.name):this.props.userinfo?.merchant_name}</View>
              {distributors && distributors.is_center && <View className='tag'>总部</View>}
             {!this.state.logintypeNum &&(<View  className='mobile'>账号:{this.props.userinfo?.mobile}</View>)}
            </View>
            {!!this.state.logintypeNum && (<View className='switch-shop' onClick={this.switchShopHandle}>
              {/* <Text className='iconfont icon-qiehuan1'></Text> */}
              <Text>切换店铺</Text>
            </View>)}
          </View>
        </View>
        {!!this.state.logintypeNum && (
          <>
            <View className='joker'></View>
            <View className='formBox'>
              {/* <Form onSubmit={this.formSubmit.bind(this)}> */}
              <View className='photoBox'>
                <View className='title'>
                  {/* <Text className='iconfont icon-zu1684'></Text> */}
                  <Text>我的头像</Text>
                </View>
                <View className='photo' onClick={(e) => this.handleAvatar()}>
                  <Image src={head_portrait || head}></Image>
                </View>
              </View>
              <View className='common'>
                <View  className='title'>
                  {/* <Text className='iconfont icon-shoujihao'></Text> */}
                  {/* <Image className='myiconfont ' src={require('../../assets/imgs/my/shoujihao.png')}></Image> */}
                  <Text>手机号</Text>
                </View>
                <View  className='value' onClick={(e) => this.notUpdate('手机号')}>
                  {mobile}
                </View>
              </View>
              {/* <View className='common'>
            <View className='title'>
              <Text className='iconfont icon-id'></Text>
              <Text>企业微信ID</Text>
            </View>
            <View className='value' onClick={(e) => this.notUpdate('企业微信ID')}>
              {work_userid}
            </View>
          </View> */}
              <View className='common'>
                <View className='title'>
                  {/* <Text className='iconfont icon-keai'></Text> */}
                  <Text>我的昵称</Text>
                </View>
                <View className='value'>
                  <AtInput
                    name='value'
                    type='text'
                    placeholder='昵称'
                    value={username}
                    onChange={this.usernameChange.bind(this)}
                    onBlur={this.usernameBlur.bind(this)}
                  />
                </View>
              </View>
              {(Taro.getEnv() == 'SAPP') ? (<View className='common'>
                <View className='title'>
                  {/* <Text className='iconfont icon-keai'></Text> */}
                  <Text>我的版本</Text>

                </View>
                <View className='value' >
                  {`V${plus.runtime.version}(${plus.runtime.versionCode})`}
                </View>
              </View>) : (<></>)}
              <View className='common'>
                <View className='title'>
                  {/* <Text className='iconfont icon-keai'></Text> */}
                  <Text>隐私政策</Text>

                </View>
                <View className='value' onClick={(e) => {
                  Taro.navigateTo({ url: `pages/auth/xieyiWeb?type=yinsi` })

                }}>
                  查看
                </View>
              </View>
              <View className='common'>
                <View className='title'>
                  {/* <Text className='iconfont icon-keai'></Text> */}
                  <Text>退出登录</Text>

                </View>
                <View className='value' onClick={(e) => this.loginOut('手机号')}>
                  确认退出
                </View>
              </View>
            </View>
          </>)}
        {!this.state.logintypeNum && (<>
          <View className='joker'></View>
          <AtListItem title='商家信息' arrow='right' thumb={require('../../assets/imgs/my/shangjiaxinxi.png')} onClick={() =>{Taro.navigateTo({url:'/pages/my/merchantInfo'})}}/>
          <AtListItem title='售后地址' arrow='right' thumb={require('../../assets/imgs/my/dizhi.png')} onClick={() =>{Taro.navigateTo({url:'pages/my/address'})}} />
          <AtListItem title='账号设置' arrow='right' thumb={require('../../assets/imgs/my/zhanghaoshezhi.png')} onClick={() =>{Taro.navigateTo({url:'pages/my/editInfo'})}}/>
          <AtListItem title='数据分析' arrow='right' thumb={require('../../assets/imgs/my/shujufenxi.png')} onClick={() =>{Taro.navigateTo({url:'pages/my/record'})}}/>
          {(Taro.getEnv() == 'SAPP') && (<AtListItem title='检查更新' arrow='right' extraText={`V${plus.runtime.version}(${plus.runtime.versionCode})`} thumb={require('../../assets/imgs/my/gengxin.png')} />)}
          <AtListItem title='清除缓存' arrow='right' thumb={require('../../assets/imgs/my/qingchu.png')} />
          <AtListItem title='退出登录' arrow='right' thumb={require('../../assets/imgs/my/tuichu.png')} onClick={(e) => this.loginOut('手机号')} />
        </>)}
        {/* </Form> */}
        <View className='bottom-div'></View>
        <AtMessage />
      </View>
    )
  }
}
